package com.donger.common.data.aop;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.donger.common.client.upms.service.RpcDictService;
import com.donger.common.core.constant.CommonConstants;
import com.donger.common.core.utils.Result;
import com.donger.common.data.annotation.Dict;
import com.donger.common.data.annotation.DictMethod;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Aspect
@Component
@Slf4j
public class DictAspect {
    @Autowired
    private RpcDictService rpcDictService;

    // 定义切点Pointcut
    @Pointcut(value = "@annotation(com.donger.common.data.annotation.DictMethod)")
    public void excudeService() {
    }

    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object result = pjp.proceed();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Object target = pjp.getTarget();
        Method currentMethod = target.getClass().getMethod(signature.getName(), signature.getParameterTypes());
        DictMethod dictMethod = currentMethod.getAnnotation(DictMethod.class);
        if (dictMethod.value()) {
            this.parseDictText(result);
        }
        return result;
    }

    /**
     * 解析
     *
     * @param result
     */
    private void parseDictText(Object result) {
        if (result instanceof Result) {
            // IPage 类型的
            if (((Result) result).getData() instanceof IPage) {
                List<JSONObject> items = new ArrayList<>();
                for (Object record : ((IPage) ((Result) result).getData()).getRecords()) {
                    items.add(translateObject(record));
                }
                ((IPage) ((Result) result).getData()).setRecords(items);
            } else if (((Result) result).getData() instanceof List) {
                List<JSONObject> items = new ArrayList<>();
                for (Object record : ((List) ((Result) result).getData())) {
                    items.add(translateObject(record));
                }
            } else {
                if(((Result) result).getData()!=null){
                    JSONObject items = new JSONObject();
                    items = translateObject(((Result) result).getData());
                    ((Result) result).setData(items);
                }
            }
        }
    }


    /**
     * 返回翻译出结果的属性
     *
     * @param record
     * @return
     */
    private JSONObject translateObject(Object record) {
        ObjectMapper mapper = new ObjectMapper();
        String json = "{}";
        try {
            mapper.registerModule(new JavaTimeModule());
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            json = mapper.writeValueAsString(record);
        } catch (JsonProcessingException e) {
            log.error("json解析失败" + e.getMessage(), e);
        }
        JSONObject item = JSONUtil.parseObj(json);
        for (Field field : record.getClass().getDeclaredFields()) {
            //update-end--Author:scott  -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
            if (field.getAnnotation(Dict.class) != null) {
                String code = field.getAnnotation(Dict.class).dicCode();
                String text = field.getAnnotation(Dict.class).dicText();
                String table = field.getAnnotation(Dict.class).dictTable();
                String key = String.valueOf(item.get(field.getName()));

                //翻译字典值对应的txt
                String textValue = translateDictValue(code, text, table, key);
                item.set(field.getName() + CommonConstants.DICT_TEXT_SUFFIX, textValue);
            }
        }
        return item;
    }

    /**
     * 返回翻译出结果的属性
     *
     * @param record
     * @return
     */
    private JSONObject translateOneObject(Object record) {
        ObjectMapper mapper = new ObjectMapper();
        String json = "{}";
        try {
            mapper.registerModule(new JavaTimeModule());
            mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
            json = mapper.writeValueAsString(record);
        } catch (JsonProcessingException e) {
            log.error("json解析失败" + e.getMessage(), e);
        }
        JSONObject item = JSONUtil.parseObj(json);
        for (Field field : record.getClass().getDeclaredFields()) {
            //update-end--Author:scott  -- Date:20190603 ----for：解决继承实体字段无法翻译问题------
            if (field.getAnnotation(Dict.class) != null) {
                String code = field.getAnnotation(Dict.class).dicCode();
                String text = field.getAnnotation(Dict.class).dicText();
                String table = field.getAnnotation(Dict.class).dictTable();
                String key = String.valueOf(item.get(field.getName()));

                //翻译字典值对应的txt
                String textValue = translateDictValue(code, text, table, key);
                item.set(field.getName() + CommonConstants.DICT_TEXT_SUFFIX, textValue);
            }else{

            }item.set(field.getName(), String.valueOf(item.get(field.getName())));
        }
        return item;
    }


    /**
     * 翻译字典文本
     *
     * @param code
     * @param text
     * @param table
     * @param key
     * @return
     */
    private String translateDictValue(String code, String text, String table, String key) {
        if (StrUtil.isEmpty(key)) {
            return "";
        }
        StringBuilder textValue = new StringBuilder();
        String[] keys = key.split(",");
        for (String k : keys) {
            String tmpValue = null;
            log.debug(" 字典 key : " + k);
            if (k.trim().length() == 0) {
                continue; //跳过循环
            }
            if (!StringUtils.isEmpty(table)) {
                tmpValue = rpcDictService.queryTableDictTextByKey(table, text, code, k.trim());
            } else {
                tmpValue = rpcDictService.queryDictTextByKey(code, k.trim());
            }

            if (StrUtil.isNotBlank(tmpValue)) {
                if (!"".equals(textValue.toString())) {
                    textValue.append(",");
                }
                textValue.append(tmpValue);
            }

        }
        return textValue.toString();
    }

}
